package dto;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

import com.sun.mail.imap.IMAPFolder;
 
public class imap {
 
    /**
     * Returns a Properties object which is configured for a POP3/IMAP server
     *
     * @param protocol either "imap" or "pop3"
     * @param host
     * @param port
     * @return a Properties object
     */
    private Properties getServerProperties(String protocol, String host,String port) {
        Properties properties = new Properties();
 
        // server setting
        properties.put(String.format("mail.%s.host", protocol), host);
        properties.put(String.format("mail.%s.port", protocol), port);
 
        // SSL setting
        properties.setProperty(String.format("mail.%s.socketFactory.class", protocol),"javax.net.ssl.SSLSocketFactory");
        properties.setProperty(String.format("mail.%s.socketFactory.fallback", protocol),"false");
        properties.setProperty(String.format("mail.%s.socketFactory.port", protocol), String.valueOf(port));
 
        return properties;
    }
 
    /**
     * Downloads new messages and fetches details for each message.
     * @param protocol
     * @param host
     * @param port
     * @param userName
     * @param password
     */
    public void downloadEmails(String protocol, String host, String port, String userName, String password) {
        Properties properties = getServerProperties(protocol, host, port);
        Session session = Session.getDefaultInstance(properties);
 
        try {
            // connects to the message store
            Store store = session.getStore(protocol);
            store.connect(userName, password);
 
            // opens the inbox folder
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);
 
            // fetches new messages from server
            
            javax.mail.Folder [] folders = store.getDefaultFolder().list("*");
            Message[] messages = folderInbox.getMessages();
            for (javax.mail.Folder folder : folders) {
    	        if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
    	            System.out.println(folder.getFullName() + ": " + folder.getMessageCount()); // 이름과 메시지 갯수 
    	            System.out.println("안 읽은 갯수" + folder.getUnreadMessageCount()); //안 읽은 갯수
    	            IMAPFolder f = (IMAPFolder) store.getFolder(folder.getFullName());
    	            if(!f.isOpen()) f.open(Folder.READ_WRITE);
    	            Message[] m = f.getMessages();
    	            
    	            System.out.println("No of Messages : " + folder.getMessageCount());
    	            System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
    	            System.out.println(m.length);
    	            for (int i=0; i < m.length;i++) 
    	            {

    	              System.out.println("*****************************************************************************");
    	              System.out.println("MESSAGE " + (i + 1) + ":");
    	              Message ms =  m[i];
    	              //System.out.println(msg.getMessageNumber());
    	              //Object String;
    	              //System.out.println(folder.getUID(msg)

    	              String sub = ms.getSubject();

    	              System.out.println("Subject: " + sub);
    	              System.out.println("From: " + ms.getFrom()[0]);
    	             System.out.println("To: "+ms.getAllRecipients()[0]);
    	              System.out.println("Date: "+ms.getReceivedDate());
    	              System.out.println("Size: "+ms.getSize());
    	              System.out.println(ms.getFlags());
    	              //System.out.println("Body: \n"+ ms.getContent());
    	              System.out.println(ms.getContentType());

    	            }
    	           //
    	          /*  for(int i = 0; i< folder.getMessageCount(); i++){
    	            	System.out.println(folder.get));
    	            }*/
    	        }
    	    }
            	
           
            for (int i = 0; i < messages.length; i++) {
                Message msg = messages[i];
                Address[] fromAddress = msg.getFrom();
                String from = fromAddress[0].toString();
                String subject = msg.getSubject();
                String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                String sentDate = msg.getSentDate().toString();
                
 
                String contentType = msg.getContentType();
                String messageContent = "";
 
                if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                        	messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                }
 
                // print out details of each message
                System.out.println("Message #" + (i + 1) + ":");
                System.out.println("\t From: " + from);
                System.out.println("\t To: " + toList);
                System.out.println("\t CC: " + ccList);
                System.out.println("\t Subject: " + subject);
                System.out.println("\t Sent Date: " + sentDate);
                System.out.println("\t Message: " + messageContent);
                System.out.println("\t received Date :" + msg.getReceivedDate()); // 받은 날짜 
                System.out.println("\t size :" + msg.getSize()); // 받은 날짜 
               
             
            }
            
            /*// 삭제 메소드 ?  
            Folder trash = store.getFolder("[Gmail]/Bin");
            for (Message m : msgs) {
                inbox.copyMessages(new Message[] { m }, trash);
            }*/
            // 삭제 메소드2
            /*if (message.getSubject().contains("Promo")) {
                message.setFlag(Flags.Flag.DELETED, true);
            }*/
 
            // disconnect
            folderInbox.close(false);
            store.close();
            
           // folder 
        } catch (NoSuchProviderException ex) {
            System.out.println("No provider for protocol: " + protocol);
            ex.printStackTrace();
        } catch (MessagingException ex) {
            System.out.println("Could not connect to the message store");
            ex.printStackTrace();
        }
        
        
        
    }
 
    /**
     * Returns a list of addresses in String format separated by comma
     *
     * @param address an array of Address objects
     * @return a string represents a list of addresses
     */
    private String parseAddresses(Address[] address) {
        String listAddress = "";
 
        if (address != null) {
            for (int i = 0; i < address.length; i++) {
                listAddress += address[i].toString() + ", ";
            }
        }
        if (listAddress.length() > 1) {
            listAddress = listAddress.substring(0, listAddress.length() - 2);
        }
 
        return listAddress;
    }
 
    /**
     * Test downloading e-mail messages
     */
    public static void main(String[] args) {
        // for POP3
        //String protocol = "pop3";
        //String host = "pop.gmail.com";
        //String port = "995";
 
 /*       // for IMAP
        String protocol = "imap";
        String host = "imap.gmail.com";
        String port = "993"; 
 
        String userName = "ituniverse10@gmail.com";
        String password = "jungho0732";*/
 
    	 String protocol = "imap";
         String host = "imap.naver.com";
         String port = "993"; 
  
         String userName = "9571907@naver.com";
         String password = "dnflwlq1";
         
        imap receiver = new imap();
        receiver.downloadEmails(protocol, host, port, userName, password);
    }
}
